package mammuthus.web.action

import org.springframework.web.bind.annotation.{RequestParam, RequestMethod, RequestMapping}
import javax.servlet.http.HttpServletRequest
import net.liftweb.{json => SJSon}
import mammuthus.web.bean.ShellResult
import scala.collection.JavaConversions._
import java.net.URLEncoder

/**
 * 5/28/15 WilliamZhu(allwefantasy@gmail.com)
 */
trait DockerContainerAction {
  this: DockerAction =>

  /*
    容器创建
   */
  @RequestMapping(value = Array("container_create.html"), method = Array(RequestMethod.GET))
  def containerCreate(req: HttpServletRequest,
                      @RequestParam(value = "slaves", defaultValue = "") slaves: String,
                      @RequestParam(value = "withIp", defaultValue = "") withIp: String
                       ):String = {
    //req.setAttribute("masterIp", slaveService.master)
    req.setAttribute("hostsStr", slaves)
    //req.setAttribute("slaves",slaves)
    if (withIp == "yes") {
      if (!slaveService.isDockerHostHaveBeenConfigure(slaves)) {
         req.setAttribute("msg","Docker宿主机还没有被配置过，请进行配置后再进行此项操作")
         return "error"
      }
      req.setAttribute("net", "--net=none")
    }else{
      req.setAttribute("net", "--net=bridge")
    }
    req.setAttribute("withIp",withIp)
    "dockerContainerCreate"
  }

  @RequestMapping(value = Array("container_create.html"), method = Array(RequestMethod.POST))
  def containerCreatePOST(req: HttpServletRequest) = {

    var params = putToReqAttribute(req, req.getParameterMap)

    //"--volume /host:/container"
    if(params.contains("volumeSource")  && params.contains("volumeTarget") && !params("volumeSource").isEmpty && !params("volumeTarget").isEmpty){
       params = params + ("--volume" -> s"${params("volumeSource")}:${params("volumeTarget")}")
    }

    //memory
    if(params.contains("memory") && !params("memory").isEmpty){
      val m = if(params("memory").matches("^\\d+(b|k|m||g)$"))
        params("memory")
      else if(params("memory").matches("^\\d+$")) s"${params("memory")}m"
      else "4g"
      params = params + ("--memory" -> m)
    }

    val urlQuery = params.filter(f => ! f._2.trim.isEmpty).map {
      f => s"${f._1}=${URLEncoder.encode(f._2, "utf-8")}"
    }.mkString("&")

    val shellResult = slaveService.runDockerContainer(urlQuery)
    logger.info("shellRes=>" + shellResult)
    val containerId = if (shellResult.success) shellResult.taskInfos(0).message else "-"

    val nextPathTuple = if(params.contains("withIp")&&params("withIp")!="yes"){
      (s"/docker/containers.html?slaves=${params("slaves")}", "完成")
    }else{
      (s"/docker/container_ip_configure.html?slaves=${params("slaves")}&containerId=${containerId}&name=${params("name")}", "指定ip")
    }

    nav(req, shellResult,
      prePath = (s"/docker/container_create.html?slaves=${params("slaves")}", "创建容器"),
      nextPath = nextPathTuple
    )
    "shellCommandExecuteResult"

  }


  //容器ip配置

  @RequestMapping(value = Array("container_ip_configure.html"), method = Array(RequestMethod.GET))
  def containerIpConfigure(req: HttpServletRequest,
                           @RequestParam(value = "containerId", defaultValue = "") containerId: String,
                           @RequestParam(value = "slaves", defaultValue = "") slaves: String
                            ) = {
    putToReqAttribute(req)
    "dockerContainerIP"
  }

  @RequestMapping(value = Array("container_ip_configure.html"), method = Array(RequestMethod.POST))
  def containerIpConfigurePOST(req: HttpServletRequest) = {
    val urlQuery = encodeFromMapToUrlQuery(req.getParameterMap)
    val shellResult = slaveService.configDockerConainerIp(urlQuery)
    nav(req, shellResult,
      prePath = (s"/docker/container_ip_configure.html?$urlQuery", "指定ip"),
      nextPath = (s"/docker/container_host_configure.html?$urlQuery", "修改host")
    )

    "shellCommandExecuteResult"
  }

  //容器host修改
  @RequestMapping(value = Array("container_host_configure.html"), method = Array(RequestMethod.GET))
  def containerHostConfigure(req: HttpServletRequest) = {
    putToReqAttribute(req)
    "dockerContainerHostConfigure"
  }


  @RequestMapping(value = Array("container_host_configure.html"), method = Array(RequestMethod.POST))
  def containerHostConfigurePost(req: HttpServletRequest) = {
    val params = putToReqAttribute(req)
    val urlQuery = encodeFromMapToUrlQuery(req.getParameterMap)
    val shellResult = slaveService.configDockerContainerHost(params("slaves"), params("name"), params("ip"))
    nav(req, shellResult,
      prePath = (s"/docker/container_host_configure.html?$urlQuery", "修改host"),
      nextPath = (s"/docker/container_start_agent.html?$urlQuery", "启动Agent")
    )
    "shellCommandExecuteResult"
  }

  //启动agent
  @RequestMapping(value = Array("container_start_agent.html"), method = Array(RequestMethod.GET))
  def containerStartAgentConfigure(req: HttpServletRequest) = {
    val params = putToReqAttribute(req)
    val urlQuery = encodeFromMapToUrlQuery(req.getParameterMap)
    val shellReults = slaveService.startDockerContainerAgent(params("slaves"), params("name"))
    nav(req, shellReults(1),
      prePath = (s"/docker/container_ip_configure.html?$urlQuery", "启动Agent"),
      nextPath = (s"/docker/containers.html?slaves=${params("slaves")}", "完成")
    )
    "shellCommandExecuteResult"
  }

  @RequestMapping(value = Array("container_enable_conf.html"), method = Array(RequestMethod.GET))
  def containerEnableConf(req: HttpServletRequest) = {
     putToReqAttribute(req)
     req.setAttribute("servers",slaveService.appSlave("zookeeper",false).mkString(","))
    "dockerContainerEnableConf"
  }
  @RequestMapping(value = Array("container_enable_conf.html"), method = Array(RequestMethod.POST))
  def containerEnableConfPost(req: HttpServletRequest) = {
    val params = putToReqAttribute(req)
    slaveService.eanbleContainerConf(params("name"))
    nav(req, ShellResult(true,"","",List()),
      prePath = (s"#", ""),
      nextPath = (s"/docker/containers.html?slaves=${params("slaves")}", "完成")
    )
    "shellCommandExecuteResult"
  }
}
